//
//  MSChatVC.m
//  MS
//
//  Created by Yuan on 13-2-26.
//  Copyright (c) 2013年 He Yuan. All rights reserved.
//

// TODO: Rename to CHAT_BAR_HEIGHT_1, etc.

#define kChatBarHeight1                      40
#define kChatBarHeight4                      94
#define SentDateFontSize                     13
#define MESSAGE_SENT_DATE_LABEL_HEIGHT       (SentDateFontSize+7)
#define MessageFontSize                      16
#define MESSAGE_TEXT_WIDTH_MAX               180
#define MESSAGE_MARGIN_TOP                   7
#define MESSAGE_MARGIN_BOTTOM                10
#define TEXT_VIEW_X                          40   // 40  (with CameraButton)
#define TEXT_VIEW_Y                          2
#define TEXT_VIEW_WIDTH                      220 // 216 (with CameraButton)
#define TEXT_VIEW_HEIGHT_MIN                 90
#define ContentHeightMax                     80
#define MESSAGE_COUNT_LIMIT                  50
#define MESSAGE_SENT_DATE_SHOW_TIME_INTERVAL 13*60 // 13 minutes
#define MESSAGE_SENT_DATE_LABEL_TAG          100
#define MESSAGE_BACKGROUND_IMAGE_VIEW_TAG    101
#define MESSAGE_TEXT_LABEL_TAG               102
#define MESSAGE_AVATAR_IMAGE_TAG             103
#define MESSAGE_CONTENT_IMAGE_TAG            104
#define MESSAGE_DATE_TAG            105
#define AVATAR_IMAGE_WIDTH                   24


#define MESSAGE_TEXT_SIZE_WITH_FONT(message, font) \
[message sizeWithFont:font constrainedToSize:CGSizeMake(MESSAGE_TEXT_WIDTH_MAX, CGFLOAT_MAX) lineBreakMode:UILineBreakModeWordWrap]

#define UIKeyboardNotificationsObserve() \
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; \
[notificationCenter addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; \
[notificationCenter addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil]

#define UIKeyboardNotificationsUnobserve() \
[[NSNotificationCenter defaultCenter] removeObserver:self];

#import "MSChatVC.h"
#import <QuartzCore/QuartzCore.h>
#import "UIColor+ColorUtils.h"
#import "PlaceholderTextView.h"
#import "UIImageView+WebCache.h"

#import "ZoomImageView.h"

@interface MSChatVC () <UITableViewDelegate, UITableViewDataSource, UITextViewDelegate>
{
    UIImage *_messageBubbleMe;
    
    UIImage *_messageBubbleOther;
    
    CGFloat _previousTextViewContentHeight;

    NSMutableArray *_chatHistorys;
    
    NSMutableArray *_heightForRow;
    
    NSNumber *tuid;
}

@end

@implementation MSChatVC

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (id)initWithInfo:(NSDictionary *)info
{
    self = [super init];
    
    if (self)
    {
        self.title = [info objectForKey:@"t_user_name"];
        
        tuid = [NSNumber numberWithInt:[[info objectForKey:@"tuid"] intValue]];
        
        _chatHistorys = [[NSMutableArray alloc]init];
        
        _heightForRow = [NSMutableArray arrayWithCapacity:1000]; // +3 in case I send/receive more messages
        
        _messageBubbleMe = [[UIImage imageNamed:@"chat_bg_me"] stretchableImageWithLeftCapWidth:23 topCapHeight:15];
        
        _messageBubbleOther = [[UIImage imageNamed:@"chat_bg_other"] stretchableImageWithLeftCapWidth:15 topCapHeight:13];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];

    }
    return self;
}

-(void)loadView
{
    [super loadView];

    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-kChatBarHeight1)];
    _tableView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = [UIColor colorWithString:@"#f1eee9"];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    
    UIImageView *messageInputBar = [[UIImageView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height-kChatBarHeight1, self.view.frame.size.width, kChatBarHeight1)];
    messageInputBar.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin);
    messageInputBar.opaque = YES;
    messageInputBar.userInteractionEnabled = YES; // makes subviews tappable
    messageInputBar.image = [[UIImage imageNamed:@"chat_inputview_bg"] resizableImageWithCapInsets:UIEdgeInsetsMake(19, 3, 19, 3)]; // 8 x 40

    UIImage *picImage = [UIImage imageNamed:@"chat_camera"];
    self.pictureButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _pictureButton.frame = CGRectMake(5.0,6.0, picImage.size.width, picImage.size.height);
    [_pictureButton setImage:picImage forState:UIControlStateNormal];
    _pictureButton.autoresizingMask = (UIViewAutoresizingFlexibleTopMargin /* multiline input */ | UIViewAutoresizingFlexibleLeftMargin /* landscape */);
    [_pictureButton addTarget:self action:@selector(sendImage:) forControlEvents:UIControlEventTouchUpInside];
    [messageInputBar addSubview:_pictureButton];
    
    _textView = [[PlaceholderTextView alloc] initWithFrame:CGRectMake(TEXT_VIEW_X, TEXT_VIEW_Y, TEXT_VIEW_WIDTH, TEXT_VIEW_HEIGHT_MIN) drawoffsety:8.5];
    _textView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    _textView.delegate = self;
    _textView.backgroundColor = [UIColor colorWithWhite:245/255.0f alpha:1];
    _textView.scrollIndicatorInsets = UIEdgeInsetsMake(13, 0, 8, 6);
    _textView.scrollsToTop = NO;
    _textView.font = [UIFont systemFontOfSize:MessageFontSize];
    _textView.placeholder = NSLocalizedString(@"请输入发送的内容", nil);
    [messageInputBar addSubview:_textView];
    _previousTextViewContentHeight = MessageFontSize+20;

    UIImageView *messageInputBarBackgroundImageView = [[UIImageView alloc] initWithImage:[[UIImage imageNamed:@"MessageInputFieldBackground"] resizableImageWithCapInsets:UIEdgeInsetsMake(20, 12, 18, 18)]]; // 32 x 40
    messageInputBarBackgroundImageView.frame = CGRectMake(TEXT_VIEW_X-2, 0, TEXT_VIEW_WIDTH+2, kChatBarHeight1);
    messageInputBarBackgroundImageView.autoresizingMask = _tableView.autoresizingMask;
    [messageInputBar addSubview:messageInputBarBackgroundImageView];
    
    // Create sendButton.
    UIImage *sendImg = [UIImage imageNamed:@"chat_send"];
    self.sendButton = [UIButton buttonWithType:UIButtonTypeCustom];
    CGFloat btnwidth = 1.7*sendImg.size.width;
    _sendButton.frame = CGRectMake(messageInputBar.frame.size.width-btnwidth-5, 8, btnwidth, sendImg.size.height);
    _sendButton.autoresizingMask = (UIViewAutoresizingFlexibleTopMargin /* multiline input */ | UIViewAutoresizingFlexibleLeftMargin /* landscape */);
    UIImage *sendButtonBackgroundImage = [sendImg stretchableImageWithLeftCapWidth:10 topCapHeight:10];
    [_sendButton setBackgroundImage:sendButtonBackgroundImage forState:UIControlStateNormal];
    [_sendButton setBackgroundImage:sendButtonBackgroundImage forState:UIControlStateDisabled];
    _sendButton.titleLabel.font = FONT_NORMAL_BOLD;
    _sendButton.titleLabel.shadowOffset = CGSizeMake(0.0, -1.0);
    [_sendButton setTitle:HYLocalizedString(@"发送") forState:UIControlStateNormal];
    [_sendButton setTitleShadowColor:[UIColor colorWithRed:0.325f green:0.463f blue:0.675f alpha:1] forState:UIControlStateNormal];
    [_sendButton addTarget:self action:@selector(sendMessage) forControlEvents:UIControlEventTouchUpInside];
    [messageInputBar addSubview:_sendButton];
    
    
    [self.view addSubview:messageInputBar];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self scrollToBottomAnimated:NO];
}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    UIKeyboardNotificationsObserve();

    [_tableView flashScrollIndicators];
}

- (void)viewWillDisappear:(BOOL)animated {
    UIKeyboardNotificationsUnobserve(); // as soon as possible

    [super viewWillDisappear:animated];
}


- (void)viewDidLoad
{
    [super viewDidLoad];

    [self setTitle:self.title showBackButton:YES];

	// Do any additional setup after loading the view.
    [self requestMessage];
}

- (void)configureViews:(BOOL)animation
{
    [super configureViews:animation];
}

-(void)requestMessage
{
    [WebService  getRequestAction:APIGetPrivateMessageDetail
                            param:[NSDictionary dictionaryWithObjectsAndKeys:
                                   [[MSSetting sharedSetting]getAccountID],@"uid",
                                   tuid,@"tuid",
                                   nil]
                          success:^(NSDictionary *info,NSError *error)
     {
         if (error == nil)
         {
             [_heightForRow removeAllObjects];
             [_chatHistorys removeAllObjects];
             NSArray *arr = [info objectForKey:@"result"];
             [_chatHistorys addObjectsFromArray:arr];
             [_tableView reloadData];
             [self textViewDidChange:_textView];
             HYLog(@"%@",info);
         }
         [MSTool showError:error];
     } failure:^(id info ,NSError *error){
         [MSTool showError:error];
     } progress:self.navigationController.view];
}

-(void)sendImage:(UIButton *)btn
{
    UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:HYLocalizedString(@"取消") destructiveButtonTitle:nil otherButtonTitles:HYLocalizedString(@"拍照"),HYLocalizedString(@"从相册选择"), nil];
    sheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
    [sheet showInView:self.navigationController.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == actionSheet.cancelButtonIndex)
    {
        return;
    }
    else if(buttonIndex == 0)
    {
        [self performSelector:@selector(takePhoto) withObject:nil afterDelay:0.0];
    }
    else if(buttonIndex == 1)
    {
        [self performSelector:@selector(openPhotoLibrary) withObject:nil afterDelay:0.0];
    }
}

-(void)openPhotoLibrary
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = NO;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentModalViewController:picker animated:YES];
}

//take a photo from camera
-(void)takePhoto
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
	{
		UIImagePickerController *picker = [[UIImagePickerController alloc] init];
		picker.delegate = self;
		picker.allowsEditing = NO;
		picker.sourceType = UIImagePickerControllerSourceTypeCamera;
		[self presentModalViewController:picker animated:YES];
	}
    else
    {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:HYLocalizedString(@"设备不支持拍照") message:nil delegate:nil cancelButtonTitle:HYLocalizedString(@"确定") otherButtonTitles:nil, nil];
        [alert show];
    }
}


#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
	// TODO, improve change the resolution of the edited image
    //	UIImage *originalImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    NSAssert(image != nil, @"Can't get the image!");
	if (image)
	{
        //上传图片        
        [self uploadImage:image];
    }
	[picker dismissModalViewControllerAnimated:YES];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissModalViewControllerAnimated:YES];
}


-(void)uploadImage:(UIImage *)image
{
    NSDictionary *p = [NSDictionary dictionaryWithObjectsAndKeys:
                       APISendPrivateImageMessage,@"action",
                       nil];
    [WebService uploadImage:image param:p labelText:HYLocalizedString(@"发送图片") success:^(NSDictionary *info,NSError *error)
     {
         HYLog(@"%@",info);
         NSDictionary *result = [info objectForKey:@"result"];
         if (result && [result isKindOfClass:[NSDictionary class]] &&[result count]>0)
         {
             [self sendMessage:[result objectForKey:@"imgs"]];
         }
     } failure:^(id info ,NSError *error){
         [MSTool showAlert:error.localizedDescription];
     }];
}

- (void)sendMessage
{
    [self sendMessage:@""];
}

- (void)sendMessage:(NSString *)img
{
    if (img || [_textView.text length]>0)
    {
        NSDictionary *p = [NSDictionary dictionaryWithObjectsAndKeys:
                           [[MSSetting sharedSetting]getAccountID],@"uid",
                           tuid,@"tuid",
                           _textView.text,@"message",
                           [NSArray arrayWithObject:img],@"pics",
                           nil];
        [WebService  getRequestAction:APISendPrivateMessage
                                param:p
                              success:^(NSDictionary *info,NSError *error)
         {
             HYLog(@"%@",info);
             if (error == nil)
             {
                 [self requestMessage];
                 _textView.text = nil;
             }
             [MSTool showError:error];
         } failure:^(id info ,NSError *error){
             [MSTool showError:error];
         } progress:self.navigationController.view];
    }
    [_textView resignFirstResponder];
    [self textViewDidChange:_textView];
}

#pragma mark - Keyboard Notifications

- (void)keyboardWillShow:(NSNotification *)notification
{
    NSTimeInterval animationDuration;
    UIViewAnimationCurve animationCurve;
    CGRect frameEnd;
    NSDictionary *userInfo = [notification userInfo];
    [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&animationCurve];
    [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&animationDuration];
    [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&frameEnd];
    
    [UIView animateWithDuration:animationDuration delay:0.0 options:(UIViewAnimationOptionsFromCurve(animationCurve) | UIViewAnimationOptionBeginFromCurrentState) animations:^{
        CGFloat viewHeight = [self.view convertRect:frameEnd fromView:nil].origin.y;
        UIView *messageInputBar = _textView.superview;
        UIViewSetFrameY(messageInputBar, viewHeight-messageInputBar.frame.size.height);
        _tableView.contentInset = _tableView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, self.view.frame.size.height-viewHeight, 0);
        [self scrollToBottomAnimated:NO];
    } completion:nil];
}

-(void)keyboardWillHide:(NSNotification *)notification
{
    [self keyboardWillShow:notification];
}

- (void)scrollToBottomAnimated:(BOOL)animated {
    NSInteger numberOfRows = [_tableView numberOfRowsInSection:0];
    if (numberOfRows) {
        [_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:numberOfRows-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:animated];
    }
}


#pragma mark UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView {
    // Change height of _tableView & messageInputBar to match textView's content height.
    CGFloat textViewContentHeight = textView.contentSize.height;
    CGFloat changeInHeight = textViewContentHeight - _previousTextViewContentHeight;
    //    NSLog(@"textViewContentHeight: %f", textViewContentHeight);
    
    if (textViewContentHeight+changeInHeight > kChatBarHeight4+2) {
        changeInHeight = kChatBarHeight4+2-_previousTextViewContentHeight;
    }
    
    if (changeInHeight) {
        [UIView animateWithDuration:0.2 animations:^{
            _tableView.contentInset = _tableView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, _tableView.contentInset.bottom+changeInHeight, 0);
            [self scrollToBottomAnimated:NO];
            UIView *messageInputBar = _textView.superview;
            messageInputBar.frame = CGRectMake(0, messageInputBar.frame.origin.y-changeInHeight, messageInputBar.frame.size.width, messageInputBar.frame.size.height+changeInHeight);
        } completion:^(BOOL finished) {
            [_textView updateShouldDrawPlaceholder];
        }];
        _previousTextViewContentHeight = MIN(textViewContentHeight, kChatBarHeight4+2);
    }
    
    // Enable/disable sendButton if textView.text has/lacks length.
    if ([textView.text length]) {
        _sendButton.enabled = YES;
        _sendButton.titleLabel.alpha = 1;
    } else {
        _sendButton.enabled = NO;
        _sendButton.titleLabel.alpha = 0.5f; // Sam S. says 0.4f
    }
}


#pragma mark - UITableViewDataSource

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [_chatHistorys count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{    
    NSDictionary *message = [_chatHistorys objectAtIndex:indexPath.row];
    
    NSArray *messageDetails = nil;
    if ([_heightForRow count] > indexPath.row) {
        messageDetails = _heightForRow[indexPath.row];
    }
    
    CGFloat messageSentDateLabelHeight = 0;
    CGFloat messageTextLabelHeight;
    if (messageDetails) {
        messageSentDateLabelHeight = [messageDetails[0] floatValue];
        messageTextLabelHeight = [messageDetails[1] CGSizeValue].height;
    }
    else
    {
        NSString *imageurl = [message objectForKey:@"src"];
        CGSize messageTextLabelSize;
        if (imageurl && [imageurl length]>0)
        {
            messageTextLabelSize = CGSizeMake(100, 150);
        }
        else
        {
            messageTextLabelSize = MESSAGE_TEXT_SIZE_WITH_FONT([message objectForKey:@"message"], [UIFont systemFontOfSize:MessageFontSize]);            
        }
        messageTextLabelHeight = messageTextLabelSize.height;
        
        _heightForRow[indexPath.row] = @[@(messageSentDateLabelHeight), [NSValue valueWithCGSize:messageTextLabelSize]];
    }
    
    return messageSentDateLabelHeight+messageTextLabelHeight+MESSAGE_MARGIN_TOP+MESSAGE_MARGIN_BOTTOM;
}

#pragma mark - UITableViewDataSource

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //    NSLog(@"cellForRowAtIndexPath: %@", indexPath);
    
    NSArray *messageDetails = _heightForRow[indexPath.row];
    CGFloat messageSentDateLabelHeight = [messageDetails[0] floatValue];
    CGSize messageTextLabelSize = [messageDetails[1] CGSizeValue];
    
    UILabel *messageSentDateLabel;
    UILabel *messageTextLabel;
    UILabel *dateLabel;
    UIImageView *messageBackgroundImageView;
    UIImageView *avatarImageView;
    UIImageView *contentImageView;
    
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        // Create messageSentDateLabel.
        messageSentDateLabel = [[UILabel alloc] initWithFrame:CGRectMake(-2, 0, tableView.frame.size.width, SentDateFontSize+5)];
        messageSentDateLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        messageSentDateLabel.tag = MESSAGE_SENT_DATE_LABEL_TAG;
        messageSentDateLabel.backgroundColor = tableView.backgroundColor;          // speeds scrolling
        messageSentDateLabel.textColor = [UIColor grayColor];
        messageSentDateLabel.textAlignment = UITextAlignmentCenter;
        messageSentDateLabel.font = [UIFont boldSystemFontOfSize:SentDateFontSize];
        [cell.contentView addSubview:messageSentDateLabel];
        
        // Create messageBackgroundImageView.
        messageBackgroundImageView = [[UIImageView alloc] initWithFrame:CGRectZero];
        messageBackgroundImageView.tag = MESSAGE_BACKGROUND_IMAGE_VIEW_TAG;
        messageBackgroundImageView.backgroundColor = tableView.backgroundColor; // speeds scrolling
        [cell.contentView addSubview:messageBackgroundImageView];
        
        // Create messageTextLabel.
        messageTextLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        messageTextLabel.tag = MESSAGE_TEXT_LABEL_TAG;
        messageTextLabel.backgroundColor = [UIColor clearColor];
        messageTextLabel.numberOfLines = 0;
        messageTextLabel.lineBreakMode = UILineBreakModeWordWrap;
        messageTextLabel.font = [UIFont systemFontOfSize:MessageFontSize];
        [cell.contentView addSubview:messageTextLabel];
        
        //Create avatar
        avatarImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,10, AVATAR_IMAGE_WIDTH, AVATAR_IMAGE_WIDTH)];
        avatarImageView.tag = MESSAGE_AVATAR_IMAGE_TAG;
        avatarImageView.layer.cornerRadius = 3.0;
        avatarImageView.layer.masksToBounds = YES;
        avatarImageView.backgroundColor = tableView.backgroundColor; // speeds scrolling
        [cell.contentView addSubview:avatarImageView];
        
        contentImageView = [[UIImageView alloc] initWithFrame:CGRectZero];
        contentImageView.tag = MESSAGE_CONTENT_IMAGE_TAG;
        contentImageView.clipsToBounds = YES;
        contentImageView.userInteractionEnabled = YES;
        contentImageView.contentMode = UIViewContentModeScaleAspectFill;
        contentImageView.backgroundColor = tableView.backgroundColor; // speeds scrolling
        [cell.contentView addSubview:contentImageView];
        
        UITapGestureRecognizer *contentTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(contentTap:)];
        [contentImageView addGestureRecognizer:contentTap];
        
        dateLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        dateLabel.tag = MESSAGE_DATE_TAG;
        dateLabel.backgroundColor = [UIColor clearColor];
        dateLabel.numberOfLines = 0;
        dateLabel.lineBreakMode = UILineBreakModeWordWrap;
        dateLabel.font = [UIFont systemFontOfSize:MessageFontSize];
        [cell.contentView addSubview:dateLabel];        
    }
    else
    {
        messageSentDateLabel = (UILabel *)[cell.contentView viewWithTag:MESSAGE_SENT_DATE_LABEL_TAG];
        messageBackgroundImageView = (UIImageView *)[cell.contentView viewWithTag:MESSAGE_BACKGROUND_IMAGE_VIEW_TAG];
        messageTextLabel = (UILabel *)[cell.contentView viewWithTag:MESSAGE_TEXT_LABEL_TAG];
        avatarImageView = (UIImageView *)[cell.contentView viewWithTag:MESSAGE_AVATAR_IMAGE_TAG];
        contentImageView = (UIImageView *)[cell.contentView viewWithTag:MESSAGE_CONTENT_IMAGE_TAG];
        dateLabel = (UILabel *)[cell.contentView viewWithTag:MESSAGE_DATE_TAG];
    }
    
    // Configure cell with message.
    NSDictionary *message = [_chatHistorys objectAtIndex:indexPath.row];
    
    messageTextLabel.text = [message objectForKey:@"message"];
    
    //content image
    NSString *imageurl = [message objectForKey:@"src"];
    if (imageurl && [imageurl length]>0)
    {
        [contentImageView setImageWithURL:[NSURL URLWithString:imageurl] placeholderImage:nil];
    }
    else
    {
        [contentImageView setImage:nil];
    }
    
    //avatar
    if ([message objectForKey:@"avatar"])
    {
        [avatarImageView setImageWithURL:[NSURL URLWithString:[message objectForKey:@"avatar"]] placeholderImage:[UIImage imageNamed:@"default_img"]];
    }
    else
    {
        [avatarImageView setImage:[UIImage imageNamed:@"default_img"]];
    }
    
    CGFloat offset = 15;
    
    [contentImageView setFrame:CGRectZero];

    if ([self isSelf:[message objectForKey:@"uid"]])
    {
        // right message
        messageBackgroundImageView.frame = CGRectMake(_tableView.frame.size.width-messageTextLabelSize.width-34 - AVATAR_IMAGE_WIDTH - offset, messageSentDateLabelHeight+MessageFontSize-13, messageTextLabelSize.width+34, messageTextLabelSize.height+12);
        messageBackgroundImageView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
        messageBackgroundImageView.image = _messageBubbleMe;
        
        UIViewSetFrameX(avatarImageView, _tableView.frame.size.width-AVATAR_IMAGE_WIDTH - 10);
        avatarImageView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;

        contentImageView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
        
        messageTextLabel.frame = CGRectMake(_tableView.frame.size.width-messageTextLabelSize.width-22 - AVATAR_IMAGE_WIDTH - offset, messageSentDateLabelHeight+MessageFontSize-9, messageTextLabelSize.width+5, messageTextLabelSize.height);
        messageTextLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
        
        if (imageurl && [imageurl length]>0)
        {
            CGRect frame = messageBackgroundImageView.frame;
            [contentImageView setFrame:CGRectMake(frame.origin.x + 7, frame.origin.y + 8, frame.size.width - 20, frame.size.height - 17)];
        }
    }
    else
    {
        messageBackgroundImageView.frame = CGRectMake(AVATAR_IMAGE_WIDTH + offset, messageSentDateLabelHeight+MessageFontSize-13, messageTextLabelSize.width+34, messageTextLabelSize.height+12);
        messageBackgroundImageView.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;
        messageBackgroundImageView.image = _messageBubbleOther;
        
        UIViewSetFrameX(avatarImageView,10);
        avatarImageView.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;
        
        contentImageView.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;
        
        messageTextLabel.frame = CGRectMake(AVATAR_IMAGE_WIDTH + offset + 22, messageSentDateLabelHeight+MessageFontSize-9, messageTextLabelSize.width+5, messageTextLabelSize.height);
        messageTextLabel.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;
        
        if (imageurl && [imageurl length]>0)
        {
            CGRect frame = messageBackgroundImageView.frame;
            [contentImageView setFrame:CGRectMake(frame.origin.x + 13, frame.origin.y + 8, frame.size.width - 20, frame.size.height - 17)];
        }
    }
    
    return cell;
}

-(BOOL)isSelf:(id)obj
{    
    NSString *fuid = ([obj isKindOfClass:[NSString class]])?obj:[obj stringValue];
    return [fuid isEqualToString:[[MSSetting sharedSetting]getAccountID]];
}

-(void)contentTap:(UITapGestureRecognizer *)g
{
    UIImageView *contentImageView = (UIImageView *)g.view;
    UITableViewCell *cell = (UITableViewCell *)contentImageView.superview.superview;
    NSIndexPath *indexPath = [_tableView indexPathForCell:cell];
    NSDictionary *message = [_chatHistorys objectAtIndex:indexPath.row];
    HYLog(@"%@",message);
    NSString *picurl = [message objectForKey:@"src"];
    CGRect rect = [contentImageView convertRect:contentImageView.bounds toView:nil];
    ZoomImageView *zoom = [[ZoomImageView alloc]initWithFrame:[UIScreen mainScreen].bounds withImage:nil delegate:self withUrl:picurl withOriginRect:rect];
    [self.navigationController.view addSubview:zoom];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
